<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-row>
        <el-col :span="4">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增{{ this.title }}</el-button
          >
        </el-col>
      </el-row>
      <el-table
        :data="datas"
        border
        v-loading="listLoading"
        fit
        size="small"
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column
          type="index"
          label="#"
          align="center"
        ></el-table-column>
        <el-table-column
          v-for="column in tableColumns"
          align="center"
          :key="column.key"
          :label="column.title"
          :prop="column.key"
          :width="column.width"
        >
          <template slot-scope="scope">
            <span v-if="column.key == 'is_show'">
              <el-button
                :type="scope.row.is_show ? 'success' : 'danger'"
                size="mini"
                :icon="scope.row.is_show ? 'el-icon-check' : 'el-icon-close'"
                circle
              ></el-button>
            </span>
            <span v-else>
              {{ scope.row[column.key] }}
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="200px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleEdit(scope)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handleDelete(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 对话框表单 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="getTitle"
      width="55%"
      destroy-on-close
      @close="handleClose"
    >
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="80px"
        label-position="right"
        style="width: 95%; padding: 0 30px"
        size="small"
      >
        <el-form-item label="图片名称" prop="name">
          <el-input v-model="form.name" placeholder="图片名称"></el-input>
        </el-form-item>
        <el-form-item label="上传图片" prop="ratio">
          <el-upload
            ref="upload"
            name="image"
            action="/api/wechat/swipe_image_upload/"
            list-type="picture-card"
            :multiple="false"
            :limit="1"
            :file-list="fileList"
            :auto-upload="dialogType == 'edit' ? true : false"
            :before-upload="handleBeforeUpload"
            :on-remove="handleRemove"
            :on-preview="handlePreview"
            :on-change="handleImageChange"
            :on-success="handleSuccess"
            accept=".jpg, .jpeg, .png, .gif, .JPG, .JPEG, .PNG, .GIF"
            :headers="headerObj"
            :data="uploadData"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="链接地址" prop="path">
          <el-input v-model="form.path" placeholder="链接地址"></el-input>
        </el-form-item>
        <el-form-item label="顺序" prop="sort">
          <el-input-number
            v-model="form.sort"
            :min="1"
            :max="100"
            label="顺序"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="是否显示" prop="is_show">
          <el-switch v-model="form.is_show"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="danger" size="small" @click="dialogVisible = false"
          >取消</el-button
        >
        <el-button type="primary" size="small" @click="HandleSave"
          >保存</el-button
        >
      </div>
      <el-dialog :visible.sync="dlgImageVisible" append-to-body>
        <el-image
          style="width: 100%; min-height: 400px"
          :src="dlgImageUrl"
          fit="fill"
        ></el-image>
        <div slot="footer">
          <el-button type="danger" @click="dlgImageVisible = false" size="mini"
            >取消</el-button
          >
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  getSwipeImages,
  addSwipeImage,
  updateSwipeImage,
  delSwipeImage,
} from "@/api/wechat";

const defaultForm = {
  name: null,
  image: null,
  path: null,
  sort: null,
  is_show: true,
};

export default {
  name: "SwipeImage",
  data() {
    return {
      form: Object.assign({}, defaultForm),
      formRules: {
        name: [{ required: true, message: "请输入图片名称", trigger: "blur" }],
      },
      title: "轮播图片",
      dialogVisible: false,
      dlgImageVisible: false,
      dialogType: "new",
      datas: [],
      listLoading: true,
      fileList: [],
      dlgImageUrl: "",
      img_file: null,
      tableColumns: [
        {
          key: "name",
          title: "图片名称",
        },
        {
          key: "image",
          title: "图片地址",
        },
        {
          key: "path",
          title: "链接地址",
        },
        {
          key: "sort",
          title: "顺序",
          width: "100",
        },
        {
          key: "is_show",
          title: "是否显示",
          width: "100",
        },
      ],
    };
  },
  computed: {
    ...mapGetters(["token"]),
    getTitle() {
      return this.dialogType == "new"
        ? `新建${this.title}`
        : `编辑${this.title}`;
    },
    headerObj() {
      return {
        authorization: "JWT " + this.token,
      };
    },
    uploadData() {
      return this.form;
    },
  },
  created() {
    this.getImageList();
  },
  methods: {
    getImageList() {
      this.listLoading = true;
      getSwipeImages()
        .then((res) => {
          this.datas = res;
          this.listLoading = false;
        })
        .catch((error) => {
          console.log(error.message);
          this.$message.error("获取数据失败");
          this.listLoading = false;
        });
    },
    //关闭对话框
    handleClose() {
      this.fileList = [];
    },
    handleSuccess(res, file, filelist) {
      console.log("success:", res);
      if (this.dialogType == "new") {
        this.dialogVisible = false;
      }
      this.getImageList();
    },
    handleBeforeUpload(file) {
      console.log("handleBeforeUpload:", file);
      const isJPG =
        file.type == "image/jpeg" ||
        file.type == "image/png" ||
        file.type == "image/gif";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.warning("上传头像图片只能是 JPG/PNG/GIF 格式!");
        return isJPG;
      }
      if (!isLt2M) {
        this.$message.warning("上传头像图片大小不能超过 2MB!");
        return isLt2M;
      }

      return isJPG && isLt2M;
    },
    handleImageChange(file, fileList) {
      console.log("change:", file, fileList);
      this.fileList = fileList;
      // this.dialogType = "editImage";
    },
    //删除图片
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.fileList = fileList;
      var file_id = null;
      file_id = file.id;
      if (file_id == null) return;
      // delCaseFile(file_id)
      //   .then((res) => {
      //     const index = this.form.files.findIndex((item) => item.id == file_id);
      //     if (index > -1) {
      //       this.form.files.splice(index, 1);
      //     }
      //     this.$message.success("删除成功");
      //   })
      //   .catch((error) => {
      //     this.$message.error("删除失败");
      //   });
    },
    handlePreview(file) {
      this.dlgImageUrl = file.url;
      this.dlgImageVisible = true;
    },

    // 增加
    handleAdd() {
      this.form = Object.assign({}, defaultForm);

      this.dialogType = "new";
      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 修改
    handleEdit(scope) {
      this.fileList = [];
      this.form = Object.assign({}, scope.row);
      this.dialogType = "edit";

      this.dialogVisible = true;
      const image_obj = {
        id: scope.row.id,
        name: scope.row.name,
        url: scope.row.image,
      };
      this.fileList.push(image_obj);
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 删除
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delSwipeImage(row.id);

          this.datas.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
          this.$message.error("删除失败!");
        });
    },
    // 保存操作
    async HandleSave() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        if (this.dialogType == "new") {
          this.$refs.upload.submit();
        } else {
          delete this.form.image;
          const res = await updateSwipeImage(this.form);
          console.log(res);
          this.dialogVisible = false;
        }
        this.$nextTick(() => {
          this.getImageList();
        });
      });
    },
  },
};
</script>

<style lang='scss' scoped>
</style>